package com.jiinfo.model;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.shiro.crypto.hash.Sha256Hash;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jiinfo.util.StringUtils;
import com.jiinfo.util.UUIDUtils;

public class User extends Model<User>{

	private static final long serialVersionUID = -2929579257546666751L;
	public static final User dao = new User();

	public static String encryptPassword(String passswrod,String salt){
		if(StringUtils.isEmpty(passswrod)){
			return null;
		}
		//password为密码，salt为用户盐值，2为hash次数
		return new Sha256Hash(passswrod, salt, 2).toString();
	}
	
	public Record getUserByUsername(String username){
		return Db.findFirst("select * from t_user t where t.removed='0' and binary t.username=?",username);
	}
	
	public List<Record> getAll(){
		String sql="select r.nickname as name,r.id from t_user r where r.removed='0' ";
		return Db.find(sql);
	}
	
	public Page<Record> pagequery(Integer pageNumber,Integer pageSize,Record record){
		StringBuffer sqlExceptSelect=new StringBuffer("from t_user t "
				+ " left join t_user_role ur on ur.userId=t.id"
				+ " left join t_role r on ur.roleId=r.id "
				+ " left join t_user u on t.creator=u.id  "
				+ " where t.removed='0' "
				+ " ");
		List<Object> list=new ArrayList<Object>();
		
		
		if(!StringUtils.isEmpty(record.getStr("searchContent"))){
			sqlExceptSelect.append(" and (t.username like ? or t.nickname like ? or t.email like ? or t.cellphone like ?)");
			list.add("%"+record.getStr("searchContent")+"%");
			list.add("%"+record.getStr("searchContent")+"%");
			list.add("%"+record.getStr("searchContent")+"%");
			list.add("%"+record.getStr("searchContent")+"%");
		}
		
		sqlExceptSelect.append(" order by t.updateTime desc");
		
		if(pageNumber==null){
			pageNumber=1;
		}
		if(pageSize==null){
			pageSize=10;
		}
		return Db.paginate(pageNumber,pageSize,"select t.*,u.username creatorName",sqlExceptSelect.toString(),list.toArray());
	}
	
	public User add(User vo,String[] cks,Record currUser){
		
		Record t=User.dao.getUserByUsername(vo.getStr("username"));
		if(t!=null){
			return null;
		}
		
		User user=new User();
		user.set("id", UUIDUtils.getUUID());
		user.set("createTime", new Date());
		user.set("creator", currUser.getStr("id"));
		user.set("updateTime", new Date());
		user.set("updator", currUser.getStr("id"));
		user.set("removed", "0");
		
		user.set("username", vo.getStr("username"));
		user.set("salt", UUIDUtils.getUUID());
		user.set("password", User.encryptPassword(vo.getStr("password"), user.getStr("salt")));
		user.set("nickname", vo.getStr("nickname"));
		user.set("email", vo.getStr("email"));
		user.set("cellphone", vo.getStr("cellphone"));
		
		if(cks!=null){
			for (String ck : cks) {
				UserRole userRole=new UserRole();
				userRole.set("id", UUIDUtils.getUUID());
				userRole.set("createTime", new Date());
				userRole.set("creator", currUser.getStr("id"));
				userRole.set("updateTime", new Date());
				userRole.set("updator", currUser.getStr("id"));
				userRole.set("removed", "0");
				
				userRole.set("userId", user.getStr("id"));
				userRole.set("roleId", ck);
				
				userRole.save();
			}
		}
		
		
		user.save();
		return user;
	}
	
	public User edit(User vo,String[] cks,Record currUser){
		
		Record t=User.dao.getUserByUsername(vo.getStr("username"));
		if(t!=null&&!t.getStr("id").equals(vo.getStr("id"))){
			return null;
		}
		
		User user=User.dao.findById(vo.getStr("id"));
		user.set("updateTime", new Date());
		user.set("updator", currUser.getStr("id"));
		
		//user.set("username", vo.getStr("username"));//用户名也不能修改
		//user.set("password", vo.getStr("password"));修改的时候不允许修改密码
		user.set("nickname", vo.getStr("nickname"));
		user.set("email", vo.getStr("email"));
		user.set("cellphone", vo.getStr("cellphone"));
		
		user.update();
		
		//先删除之前的用户角色
		UserRole.dao.deleteUserRoleByUserId(user.getStr("id"));
		if(cks!=null){
			for (String ck : cks) {
				UserRole userRole=new UserRole();
				userRole.set("id", UUIDUtils.getUUID());
				userRole.set("createTime", new Date());
				userRole.set("creator", currUser.getStr("id"));
				userRole.set("updateTime", new Date());
				userRole.set("updator", currUser.getStr("id"));
				userRole.set("removed", "0");
				
				userRole.set("userId", user.getStr("id"));
				userRole.set("roleId", ck);
				
				userRole.save();
			}
		}
		
		return user;
	}
	
	public User remove(String id){
		
		//逻辑删除用户
		User user=User.dao.findById(id);
		user.set("removed", "1");
		user.update();
		
		//同时删除该用户的所属角色
		UserRole.dao.deleteUserRoleByUserId(id);
		
		
		return user;
	}
	
}
